package org.ourgrid.broker.commands.executors;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.dao.WorkerDAO;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.worker.controller.actions.RemoteExecuteMessageHandle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;

public class RemoteExecuteExecutor extends SchedulerCommandExecutor {
	
	private String workerID;
	private long requestID;
	private String commands;
	private String[] envVars;

	
	/**
	 * <REMOTE_EXECUTE workerID='String' requestID='long' commands='String'>
	 *    1..n <ENV_VAR var='String'/> 
	 * </REMOTE_EXECUTE> 
	 */
	public void execute(SchedulerData data, ServiceManager manager) {
		
		fillData(data.getXml());
		
		DeploymentID workerDeploymentID = new DeploymentID(workerID);
		Worker worker = manager.getDAO(WorkerDAO.class).getWorker(workerDeploymentID);
		
		Map<String, String> vars = new LinkedHashMap<String, String>();		
		StringTokenizer tokenizer = null;
		
		for (String var : envVars) {
			tokenizer = new StringTokenizer(var, "=");
			vars.put(tokenizer.nextToken(), tokenizer.nextToken());
		}
		
		if (worker != null) {
			worker.sendMessage(new RemoteExecuteMessageHandle(requestID, commands, vars));
		}	
	}
	
	private void fillData(String xml) {
		
		Document logDocFile = super.getXMl(xml);
		
		Element element = logDocFile.getDocumentElement();
		
		workerID = element.getAttribute("workerID");
		requestID = Long.valueOf(element.getAttribute("requestID"));
		commands = element.getAttribute("commands");
		
		int size = element.getElementsByTagName("ENV_VAR").getLength();
		envVars = new String[size];
		
		for (int i = 0; i < size; i++) {
			envVars[i] = element.getElementsByTagName("ENV_VAR").item(i).getAttributes().
									getNamedItem("var").getNodeValue();
		}
	}
}
